<template>
  <div class="admin-page-wrapper">
    <div class="admin-post-list">
      <el-card>
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
          <span style="font-size: 20px; font-weight: bold;">知途</span>
          <el-button type="primary" @click="$router.push('/admin/stats')">
            论坛活跃度统计
          </el-button>
        </div>
        <div class="header-bar">
          <h2>论坛帖子管理</h2>
          <div class="admin-info">
            <el-avatar
              v-if="user.avatar"
              :src="user.avatar"
              size="small"
              style="margin-right: 8px;"
            />
            <el-dropdown>
              <span class="el-dropdown-link">
                {{ user.username || '管理员' }}
                <el-icon><arrow-down /></el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="logout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
        <div style="display: flex; justify-content: space-between; align-items: center;">
          <el-switch
            v-model="showDeleted"
            active-text="显示已删除帖子"
            inactive-text="隐藏已删除帖子"
          />
        </div>
        <el-tabs v-model="activeTab">
          <el-tab-pane label="全部帖子" name="all">
            <el-table :data="filteredPosts" style="width: 100%; margin-top: 20px;">
              <el-table-column prop="id" label="ID" width="60" />
              <el-table-column label="标题" min-width="180">
                <template #default="scope">
                  <el-tag v-if="scope.row.isTop" type="danger" effect="plain" style="margin-right:4px;">置顶</el-tag>
                  {{ scope.row.title }}
                </template>
              </el-table-column>
              <el-table-column prop="username" label="作者" width="100" />
              <el-table-column label="内容" min-width="200">
                <template #default="scope">
                  <span>{{ scope.row.content.length > 50 ? scope.row.content.slice(0, 50) + '...' : scope.row.content }}</span>
                  <el-button type="success" size="small" link @click="showDetail(scope.row)">查看</el-button>
                </template>
              </el-table-column>
              <el-table-column prop="createTime" label="创建时间" width="170">
                <template #default="scope">
                  {{ formatDate(scope.row.createTime) }}
                </template>
              </el-table-column>
              <el-table-column label="状态" width="80">
                <template #default="scope">
                  <el-tag v-if="!scope.row.isDeleted" type="success">正常</el-tag>
                  <el-tag v-else type="info">已删除</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="220">
                <template #default="scope">
                  <template v-if="!scope.row.isDeleted">
                    <el-button
                      v-if="isAdmin && !scope.row.isTop"
                      type="primary"
                      size="small"
                      @click="setTop(scope.row.id, true)"
                    >置顶</el-button>
                    <el-button
                      v-if="isAdmin && scope.row.isTop"
                      type="warning"
                      size="small"
                      @click="setTop(scope.row.id, false)"
                    >取消置顶</el-button>
                    <el-button
                      v-if="isAdmin"
                      type="danger"
                      size="small"
                      @click="confirmDelete(scope.row.id)"
                    >删除</el-button>
                  </template>
                  <template v-else>
                    <el-button
                      v-if="isAdmin"
                      type="success"
                      size="small"
                      @click="restorePost(scope.row.id)"
                    >恢复</el-button>
                  </template>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
              background
              layout="prev, pager, next, jumper, ->, total"
              :total="total"
              :page-size="pageSize"
              :current-page="currentPage"
              @current-change="handlePageChange"
            />
          </el-tab-pane>
          <el-tab-pane label="待审核" name="pending">
            <el-table :data="pendingPosts" style="width: 100%; margin-top: 20px;">
              <el-table-column prop="id" label="ID" width="60" />
              <el-table-column prop="title" label="标题" min-width="180" />
              <el-table-column prop="username" label="作者" width="100" />
              <el-table-column prop="content" label="内容" min-width="200" />
              <el-table-column prop="createTime" label="创建时间" width="170">
                <template #default="scope">
                  {{ formatDate(scope.row.createTime) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="180">
                <template #default="scope">
                  <el-button type="success" size="small" @click="approve(scope.row.id)">通过</el-button>
                  <el-button type="danger" size="small" @click="reject(scope.row.id)">拒绝</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
              background
              layout="prev, pager, next, jumper, ->, total"
              :total="pendingTotal"
              :page-size="pendingPageSize"
              :current-page="pendingCurrentPage"
              @current-change="handlePendingPageChange"
            />
          </el-tab-pane>
          <el-tab-pane label="未通过" name="rejected">
            <el-table :data="rejectedPosts" style="width: 100%; margin-top: 20px;">
              <el-table-column prop="id" label="ID" width="60" />
              <el-table-column prop="title" label="标题" min-width="180" />
              <el-table-column prop="username" label="作者" width="100" />
              <el-table-column prop="content" label="内容" min-width="200" />
              <el-table-column prop="createTime" label="创建时间" width="170">
                <template #default="scope">
                  {{ formatDate(scope.row.createTime) }}
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
              background
              layout="prev, pager, next, jumper, ->, total"
              :total="rejectedTotal"
              :page-size="rejectedPageSize"
              :current-page="rejectedCurrentPage"
              @current-change="handleRejectedPageChange"
            />
          </el-tab-pane>
        </el-tabs>
      </el-card>
  
      <!-- 删除确认弹窗 -->
      <el-dialog v-model="showDeleteDialog" title="确认删除" width="300px" center>
        <span>确定要删除该帖子吗？</span>
        <template #footer>
          <el-button @click="showDeleteDialog = false">取消</el-button>
          <el-button type="danger" @click="doDelete">确认</el-button>
        </template>
      </el-dialog>
  
      <!-- 帖子详情弹窗 -->
      <el-dialog v-model="detailVisible" :title="detailPost.title" width="500px">
        <div style="white-space: pre-wrap;">{{ detailPost.content }}</div>
        <template #footer>
          <el-button type="primary" @click="detailVisible = false">关闭</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>
  
<script setup>
import { ref, computed, onMounted, watch, watchEffect } from 'vue'
import { getPosts, setPostTop, deletePostById, restorePostById, getPendingPosts, approvePost, rejectPost, getRejectedPosts } from '../api/post'
import { useUserStore } from '../store/user'
import { ArrowDown } from '@element-plus/icons-vue'
  
const userStore = useUserStore()
const user = userStore.user || {}
const isAdmin = computed(() => userStore.user?.isAdmin)
  
const posts = ref([])
const showDeleted = ref(false)
const showDeleteDialog = ref(false)
const deleteId = ref(null)
const detailVisible = ref(false)
const detailPost = ref({})
const activeTab = ref('all')
const pendingPosts = ref([])
const rejectedPosts = ref([])
const total = ref(0)
const pageSize = ref(10)
const currentPage = ref(1)
const pendingTotal = ref(0)
const pendingPageSize = ref(10)
const pendingCurrentPage = ref(1)
const rejectedTotal = ref(0)
const rejectedPageSize = ref(10)
const rejectedCurrentPage = ref(1)
  
const fetchPosts = async () => {
  const res = await getPosts({ page: currentPage.value - 1, size: pageSize.value })
  posts.value = res.data.data.content
  total.value = res.data.data.totalElements
}
  
const fetchPendingPosts = async () => {
  const res = await getPendingPosts({ page: pendingCurrentPage.value - 1, size: pendingPageSize.value })
  pendingPosts.value = res.data.data.content
  pendingTotal.value = res.data.data.totalElements
}
  
const fetchRejectedPosts = async () => {
  const res = await getRejectedPosts({ page: rejectedCurrentPage.value - 1, size: rejectedPageSize.value })
  rejectedPosts.value = res.data.data.content
  rejectedTotal.value = res.data.data.totalElements
}
  
const filteredPosts = computed(() =>
  posts.value.filter(post => showDeleted.value ? post.isDeleted : !post.isDeleted)
)
  
const setTop = async (postId, top) => {
  await setPostTop(postId, top)
  await fetchPosts()
}
  
const confirmDelete = (postId) => {
  deleteId.value = postId
  showDeleteDialog.value = true
}
  
const doDelete = async () => {
  await deletePostById(deleteId.value)
  showDeleteDialog.value = false
  await fetchPosts()
}
  
const restorePost = async (postId) => {
  await restorePostById(postId)
  await fetchPosts()
}
  
const showDetail = (post) => {
  detailPost.value = post
  detailVisible.value = true
}
  
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const d = new Date(dateStr)
  return d.toLocaleString()
}
  
const approve = async (id) => {
  await approvePost(id)
  await fetchPendingPosts()
}
  
const reject = async (id) => {
  await rejectPost(id)
  await fetchPendingPosts()
}
  
const handlePageChange = (page) => {
  currentPage.value = page
  fetchPosts()
}
  
const handlePendingPageChange = (page) => {
  pendingCurrentPage.value = page
  fetchPendingPosts()
}
  
const handleRejectedPageChange = (page) => {
  rejectedCurrentPage.value = page
  fetchRejectedPosts()
}
  
const logout = () => {
  userStore.logout && userStore.logout()
  window.location.href = '/login'
}
  
watch(activeTab, (val) => {
  if (val === 'pending') fetchPendingPosts()
  if (val === 'rejected') fetchRejectedPosts()
})
  
onMounted(() => {
  fetchPosts()
  fetchPendingPosts()
  fetchRejectedPosts()
  watchEffect(() => {
    console.log('posts:', posts.value)
  })
})
</script>
  
<style scoped>
.admin-page-wrapper {
  min-height: 100vh;
  background: hsl(0, 0%, 100%);
  display: flex;
  justify-content: center;
  align-items: flex-start;
  /* 左右固定边距，内容居中 */
  padding-left: 48px;
  padding-right: 48px;
  box-sizing: border-box;
}

.admin-post-list {
  width: 100%;
  max-width: 1100px;
  margin: 1px auto 0 auto;
  background: linear-gradient(135deg, #b2f0e6 0%, #fbeee6 100%);
  /* background: #fff; */
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0,0,0,0.08);
  padding: 32px 32px 24px 32px;
  box-sizing: border-box;
}

@media (max-width: 1200px) {
  .admin-post-list {
    max-width: 98vw;
    padding: 16px 8px;
  }
  .admin-page-wrapper {
    padding-left: 8px;
    padding-right: 8px;
  }
}
@media (max-width: 768px) {
  .admin-post-list {
    max-width: 100vw;
    padding: 8px 2px;
  }
  .admin-page-wrapper {
    padding-left: 0;
    padding-right: 0;
  }
}

.header-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}
.admin-info {
  display: flex;
  align-items: center;
}
.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
  font-weight: bold;
  display: flex;
  align-items: center;
}
</style>